package jsu.yym.tiktok.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jsu.yym.tiktok.pojo.ResponseResult;
import jsu.yym.tiktok.pojo.Video;
import jsu.yym.tiktok.mapper.Type;
import jsu.yym.tiktok.mapper.UserMapper;
import jsu.yym.tiktok.mapper.VideoMapper;
import jsu.yym.tiktok.server.QiniuMediaUtilService;
import jsu.yym.tiktok.server.VideoComparator;
import jsu.yym.tiktok.service.SearchService;
import jsu.yym.tiktok.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@CrossOrigin
@RestController
public class VideoController {
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private VideoService videoService;
    @Resource
    private QiniuMediaUtilService qiniuMediaUtilService;
    @Resource
    private SearchService searchService;



    //上传视频

    @RequestMapping(value = "/video/upload",method = RequestMethod.POST)
    public ResponseResult uploadFile(@RequestParam("file") MultipartFile file){
        System.out.println("进入上传视频");
        Video video = videoService.uploadVideo(file);
        if (Objects.isNull(video)) {
            return new ResponseResult(503,"上传失败");
        }
//        System.out.println("1111");
        return new ResponseResult(200,"上传成功",video);
    }

    //发布视频
    @PostMapping("/video/add")
    public ResponseResult addVideo(@RequestBody Video video) throws Exception {
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        video.setUsername(id);
        try {
            String s = qiniuMediaUtilService.TextCensor(video.getContext());
//            String s1 = resourcesCensor.ImageCensor();
//            System.out.println(resourcesCensor.getVideoCensorResultByJobID(s));
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(s);

            // 提取"suggestion"的值
            String suggestionValue = jsonNode.path("result").path("suggestion").asText();
            System.out.println(suggestionValue);
//            System.out.println(s1);
            String type = searchService.transLabel(suggestionValue);
            if(type.equals(Type.BLOCK))
                return new ResponseResult(409,"文案审核不通过");
            else if(Type.REVIEW.equals(type))
                video.setState(3);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String image = userMapper.getImageByUserName(video.getUsername());
        video.setImgUser(image);
        String s = videoService.check(video.getLabel());
        video.setLabel(s);
        int count = videoMapper.insert(video);
        if(count<=0)
            return new ResponseResult(503,"保存失败");
        //将上传的视频记录添加到es中
        videoService.saveVideoToElasticsearch(video);
        return new ResponseResult(200,"保存成功");
    }

    //发布草稿
    @PostMapping("/video/send/draft")
    public ResponseResult addDraftVideo(@RequestBody Video video)
    {
        Video v = videoMapper.getVideoByPkId(video.getPkId());
        v.setState(video.getState());
        int count = videoMapper.updateById(v);
        videoService.updateVideoInElasticsearch(v);
        if(count<=0)
            return new ResponseResult(503,"保存失败");
        return new ResponseResult(200,"保存成功");
    }

    /**
     * 删除视频
     * @param id  视频的唯一id
     * @return
     */
    @PostMapping("/video/delete/{id}")
    public ResponseResult deleteVideo(@PathVariable int id)
    {
        int count = videoMapper.deleteById(id);
        if(count<=0)
            return new ResponseResult(503,"删除失败");

        return new ResponseResult(200,"删除成功");
    }


    /**
     * 根据用户id，查找用户所有人可见的视频
     * @param
     * @return
     */
//    @PostMapping("/video/all")
//    public ResponseResult findVideoByUsername()
//    {
//        String id = null;
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if (authentication != null)
//            id = authentication.getName(); // 获取当前用户的id
//        List<Video> videos = videoMapper.getVideoByUserNameAndState(id,1);
//        List<Video> videos1 = videoMapper.getVideoByUserNameAndState(id,2);
//        videos.addAll(videos1);
//        if (videos.isEmpty()) {
//            return new ResponseResult(503,"获取失败");
//        }
//        return new ResponseResult(200,"获取成功",videos);
//    }

    /**
     * 根据用户id，查找用户自己可见的视频
     * @param
     * @return
     */
//    @PostMapping("/video/self")
//    public ResponseResult findVideoByUsernameSelf()
//    {
//        String id = null;
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if (authentication != null)
//            id = authentication.getName(); // 获取当前用户的id
//        List<Video> videos = videoMapper.getVideoByUserNameAndState(id,2);
//        if (Objects.isNull(videos)) {
//            return new ResponseResult(503,"获取失败");
//        }
//        return new ResponseResult(200,"获取成功",videos);
//    }


    @GetMapping("/video/get/hot")
    public ResponseResult getHotVideo()
    {
        List<Video> videos = videoMapper.getVideoByState(1);
        videos=new VideoComparator().sortVideos(videos);
        if (Objects.isNull(videos)) {
            return new ResponseResult(409,"还没有视频");
        }
        return new ResponseResult(200,"获取成功",videos);
    }

    /**
     * 获取所有的video,根据用户的喜好，视频的浏览量等等将视频进行排序
     * @return
     */
    @GetMapping("/video/get/{id}")
    public ResponseResult getAllVideo(@PathVariable String id) throws IOException {
        System.out.println(id);
        switch (id){
            case Type.CITY:
                return videoService.getVideoByAddress();
            case Type.RECOMMEND:
                return videoService.getVideo();
            case Type.FOCUS:
                return videoService.getFocusVideo();
            case Type.SPORTS:
                return videoService.getVideoByLabel(id);
            case Type.DAILY:
                return videoService.getVideoByLabel(id);
            case Type.STAR_GOSSIP:
                return videoService.getVideoByLabel(id);
            case Type.FILM_MUSIC:
                return videoService.getVideoByLabel(id);
            case Type.FOOD_SHOP:
                return videoService.getVideoByLabel(id);
            case Type.GAME_FICTION:
                return videoService.getVideoByLabel(id);
        }
        return new ResponseResult(400,"数据不正确");
    }


    /**
     * 获取草稿箱内的内容
     * @param
     * @return
     */
//    @GetMapping("/video/get/draft")
//    public ResponseResult getDraftVideo()
//    {
//        String id = null;
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if (authentication != null)
//            id = authentication.getName(); // 获取当前用户的id
//        List<Video> videos= videoMapper.getVideoByUserNameAndState(id,0);
//        if (Objects.isNull(videos)) {
//            return new ResponseResult(503,"获取失败");
//        }
//
//        return new ResponseResult(200,"获取成功",videos);
//    }


    /**
     * 分享视频
     * @param id 视频的id
     * @return
     */
    @PostMapping("/video/share/{id}")
    public ResponseResult shareVideo(@PathVariable int id)
    {
        //更新视频相关数据
        Video v = videoMapper.getVideoByPkId(id);
        int count = videoMapper.updateSharesByPkId(v.getShares()+1,id);
        String url = v.getSrc();
        if (Objects.isNull(url)||count<=0) {
            return new ResponseResult(503,"获取失败");
        }
        return new ResponseResult(200,"分享成功",url);
    }


    //智能生成文案
    @PostMapping("/video/generate")
    public ResponseResult generateContext(@RequestBody List<String> keywords)
    {
//        String text = videoService.generateCopy(keywords);
        String text = null;
        if (Objects.isNull(text)) {
            return new ResponseResult(503,"生成失败");
        }
        return new ResponseResult(200,"生成成功",text);
    }

    //获取用户作品--状态 0---草稿    1---所有人可见     2--自己可见
    @GetMapping("/video/user/get/{state}")
    public ResponseResult UserGetVideoByState(@PathVariable int state)
    {
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        List<Video> videos= videoMapper.getVideoByUserNameAndState(id,state);
        if (Objects.isNull(videos)) {
            return new ResponseResult(503,"获取失败");
        }

        return new ResponseResult(200,"获取成功",videos);
    }



    //获取正在审核
    @GetMapping("/video/get/not/{state}")
    public ResponseResult VideoNotAllow(@PathVariable int state) throws Exception {
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        List<Video> videos= videoMapper.selectList(null);
        List<Video> videoList = new ArrayList<>();
        for (Video v:videos) {
            if(!(v.getState()==0||v.getState()==1||v.getState()==2))
            {
                String s =searchService.changeLabel(v.getLabel());
                v.setLabel(s);
                System.out.println(s);
                videoList.add(v);
            }
        }
        if (Objects.isNull(videoList)) {
            return new ResponseResult(503,"获取失败");
        }

        return new ResponseResult(200,"获取成功",videoList);
    }

    //通过审核
    @PostMapping("/video/change/state/{id}")
    public ResponseResult videoChangeState(@PathVariable int id)
    {
        System.out.println(id);
        int count = videoMapper.updateStateByPkId(2,id);
        if(count <=0)
            return new ResponseResult(503,"失败");
        return new ResponseResult(200,"成功");
    }



}
